<?php
/**
 * @title 397. 整数替换 - 迭代+剪枝
 * @author start2004
 */

// ini_set("memory_limit", "128M");

class Solution {

    /**
     * @param Integer $n
     * @return Integer
     */
    function integerReplacement($n) {
        /**
         * @since 2020-08-12 哈希剪枝
         */
        $hashs = [];

        /**
         * @since 2020-08-12 深度
         */
        $deep = -1;

        /**
         * @since 2020-08-12 迭代
         */
        $nexts = [$n];
        while($nexts){
            /**
             * @since 2020-08-12 深度+1
             */
            $deep++;

            /**
             * @since 2020-08-12 下次迭代值
             */
            $nextsTmp = [];

            /**
             * @since 2020-08-12 检查值
             */
            foreach ($nexts as $next){
                /**
                 * @since 2020-08-12 到达终点
                 */
                if($next == 1){
                    $nextsTmp = [];
                    break;
                } else {}

                /**
                 * @since 2020-08-12 剪枝,防止重复
                 */
                if(!isset($hashs[$next])){
                    $hashs[$next] = 1;

                    /**
                     * @since 2020-08-12 偶数
                     */
                    if($next%2 == 0){
                        $nextsTmp[] = ($next>>1);
                    } else {
                        /**
                         * @since 2020-08-12 奇数
                         */
                        $nextsTmp[] = $next+1;
                        $nextsTmp[] = $next-1;
                    }
                } else {}
            }

            /**
             * @since 2020-08-12 下次迭代
             */
            $nexts = $nextsTmp;
        }

        /**
         * @return
         */
        return $deep;
    }
}



/**
 * @url http://127.0.0.1/leetcode/202008/2020.08.12_5.php
 */
$datas = [
    8,
    7,
    1,
    15,
    2,
    pow(2,31)-1,
];

include_once dirname(__DIR__) . DIRECTORY_SEPARATOR ."xhprof.php";
$xhprof = new Xhprof();
foreach ($datas as $data){
    var_dump($data);

    $obj = new Solution();
    $result = $obj->integerReplacement($data);
    var_dump($result);
    echo str_repeat("<br>", 3);
}
$xhprof->end();
